var express = require('express');
var app = express();
app.set('port', process.env.PORT || 2000);
app.disable('x-powered-by')
//设置handlebars视图引擎
var handlebars = require('express3-handlebars').create({defaultLayout: 'main'});
app.engine('handlebars', handlebars.engine);
app.set('view engine', 'handlebars');


app.use(function (req, res, next) {
    res.locals.showTests = app.get('env') !== 'production' && req.query.test === '1';
    next();
});

app.get('/', function (req,res) {
    res.render('home');
});

var fortune = require('./lib/fortune.js');
app.get('/about', function (req, res) {
    res.render('about', {
        fortune: fortune.getFortune(),
        pageTestScript: '/qa/tests-about.js'
    });
});

app.get('/headers', function (req, res) {
    res.set('Content-Type', 'text/plain')
    var s = ''
    for(var name in req.headers) s += name + ': ' + req.headers[name] + '\n'
    res.send(s)
})

app.post('/process-contact', function (req, res) {
    console.log('Received contact from ' + req.body.name + ' <' + req.body.email + '>')
    res.redirect(303, '/thank-you');
})

app.get('/tours/hood-river', function (req, res) {
    res.render('tours/hood-river');
});

app.get('/tours/request-group-rate', function (req, res) {
    res.render('tours/request-group-rate');
});

//静态资源
app.use(express.static(__dirname + '/public'));

// catch-all 处理器
app.use(function (req, res) {
    res.status(404);
    res.render('404');
});

// 500 错误处理器
app.use(function (err, req, res, next) {
    console.error(err.stack);
    res.status(500);
    res.render('500');
});

app.listen(app.get('port'), function () {
    console.log('Express started on http://localhost:' + app.get('port') + ';press Ctrl-C to terminate.');
});
